package com.zretc.shop.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zretc.shop.entity.Users;
import com.zretc.shop.mapper.UsersMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.sql.Timestamp;

@Service
public class UsersService {
    @Resource
    private UsersMapper usersMapper;

    public Object addUser(String username, String password, String nickname) {

        Users users = new Users();
        users.setUsername(username);
        users.setPassword(password);
        users.setNickname(nickname);
        users.setPoints(0.0);
        Timestamp now = new Timestamp(System.currentTimeMillis());//当前的系统时间
        users.setAddTime(now);//调用maooer 进行insert操作
        int rt = usersMapper.insert(users);//rt表示对数据作 影响了多少行 如果是1行 表示正确
        if (rt == 1) {
            return R.ok(rt);
        } else {
            return R.failed("操作失败");
        }
    }


    public Object delUser(Integer id) {
        int rt = usersMapper.deleteById(id);
        if (rt == 1) {
            return R.ok(rt);
        } else {
            return R.failed("操作失败");
        }

    }

    public Object queryById(Integer id) {
        Users users = usersMapper.selectById(id);
        if (users != null) {
            return R.ok(users);
        } else {
            return R.failed("用户不存在");
        }
    }

    public Object editById(Users users) {
        int rt = usersMapper.updateById(users);
        if (rt == 1) {
            return R.ok(users);
        } else {
            return R.failed("用户不存在");
        }
    }


    public Object queryByPage(Integer pageNo, Integer pageSize, String username) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("username", username);
        Page page = new Page(pageNo, pageSize);
        IPage<Users> iPage = usersMapper.selectPage(page, wrapper);
        return R.ok(iPage);
    }

    public Object queryUserListByName(String name) {
        List<Users> list = usersMapper.queryUserListByName(name);
        return R.ok(list);
    }

    public Object queryUserByNicknameAndUsername(String username, String nickname) {
        List<HashMap> list = usersMapper.queryUserByNicknameAndUsername(username, nickname);

        return R.ok(list);
    }

    public Object queryUserPageByNicknameAndUsername(Integer pageNo,Integer pageSize,String username, String nickname) {
        Page page = new Page(pageNo, pageSize);
        IPage<HashMap> list = usersMapper.queryUserPageByNicknameAndUsername(page, username, nickname);
        return R.ok(list);
    }
}